import {
  ExceptionFilter,
  Catch,
  ArgumentsHost,
  BadRequestException,
} from '@nestjs/common';
import { ValidationError } from 'class-validator';
import { Response } from 'express';
import ErrorCode from '../constants/errorCode';

@Catch(BadRequestException)
export class ValidationExceptionFilter implements ExceptionFilter {
  catch(exception: BadRequestException, host: ArgumentsHost) {
    const ctx = host.switchToHttp();
    const response = ctx.getResponse<Response>();
    const status = exception.getStatus();

    if (
      exception instanceof BadRequestException &&
      exception.getResponse() instanceof Array
    ) {
      const errors = exception.getResponse() as ValidationError[];
      const formattedErrors = this.formatValidationErrors(errors);

      response.status(status).json({
        code: ErrorCode.SUCCESS,
        message: formattedErrors,
      });
      console.log(formattedErrors);
    } else {
      const error = exception.getResponse() as { message: string[] };
      response.status(status).json({
        code: ErrorCode.SUCCESS,
        message: [error.message || '服务器错误'],
      });
    }
  }

  private formatValidationErrors(errors: ValidationError[]) {
    return errors.flatMap((error) => Object.values(error.constraints));
  }
}
